package com.slfx.stock.listener;

import com.slfx.stock.config.RabbitMQConfig;
import com.slfx.stock.service.StockFlowService;
import com.slfx.stock.service.StockService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Random;

@Component
public class ReduceStockLister {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private StockFlowService stockFlowService;

    @Autowired
    private StockService stockService;

    @RabbitListener(queues = RabbitMQConfig.REDUCE_STOCK_QUEUE)
    @Transactional
    public void receiveMessage(Message message){

        //获取消息id
        String messageId = message.getMessageProperties().getMessageId();
        System.out.println(messageId);

        Jedis jedis = jedisPool.getResource();

        //业务流程
        try{
            //redis锁去重校验
            if (!"OK".equals(jedis.set(messageId,messageId,"NX","PX",300000))){
                System.out.println("redis去重校验 失败 重复消息");
                return;
            }

            //mysql状态校验
            if (!(stockFlowService.findByFlag(messageId).size() ==0)){
                System.out.println("mysql去重校验 失败 重复消息");
                return;
            }

            //库存扣减
            String goodsId = null;
            try {
                goodsId = new String(message.getBody(),"utf-8");
                stockService.reduceStock(goodsId,messageId);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            int nextInt = new Random().nextInt(100);
            System.out.println("随机数："+nextInt);
            if (nextInt%2 ==0){
                int i= 1/0;
            }

        }catch (RuntimeException e){
            //释放锁
            //解锁
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            jedis.eval(script, Collections.singletonList(messageId), Collections.singletonList(messageId));
            System.out.println("出现异常了");
            System.out.println(messageId+"：释放锁");
            throw e;
        }
    }
}
